<template>
  <BaseDialog
    v-model="dialogVisible"
    :title="title"
    width="650px"
    :before-close="handleClose"
  >
    <el-form
      ref="refDialogForm"
      v-loading="formLoading"
      class="set-dialog-form"
      :label-width="language === 'en' ? '180px' : '80px'"
      :model="formData"
      :rules="rules"
    >
      <el-row>
        <el-col :span="24">
          <el-form-item prop="fileList">
            <template #label>
              <label>导入文件</label>
            </template>
            <el-upload
              ref="refUpload"
              style="width: 100%"
              v-model:file-list="formData.fileList"
              :limit="1"
              accept=".xls,.xlsx,.csv"
              :auto-upload="false"
              :on-change="handleChange"
              :on-exceed="handleExceed"
              :on-remove="handleRemove"
            >
              <template #trigger>
                <el-button type="primary">选择附件</el-button>
              </template>
              <el-button type="primary" text @click="handleDownloadTemplate"
                >下载模板</el-button
              >
              <template #tip>
                <div class="el-upload__tip">
                  导入前请先下载导入模板，单个文件不能超过1000条
                </div>
              </template>
            </el-upload>
          </el-form-item>
          <!-- <el-form-item label-position="top">
            <template #label>
              <label>导入记录：</label>
            </template>
            <div
              class="item"
              style="width: 100%; display: flex; justify-content: space-between"
              v-for="item in 5"
              :key="item"
            >
              <div class="item-left">
                2025-08-11 10:10:01 导入1000条数据，成功300条，失败700条
              </div>
              <el-button type="primary" text @click="handleViewDetail"
                >查看详情</el-button
              >
            </div>
          </el-form-item> -->
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <div class="form-dialog-footer">
        <el-button plain @click="handleClose">{{
          $t('public.cancel')
        }}</el-button>
        <el-button type="primary" @click="handleSubmitForm">{{
          $t('public.confirm')
        }}</el-button>
      </div>
    </template>
  </BaseDialog>
</template>

<script setup>
import { genFileId } from 'element-plus'

const props = defineProps({
  type: {
    type: String,
    default: '' // 1-菜谱/2-设备/3-食材/4-调料/5-工艺
  },
  title: {
    type: String,
    default: ''
  }
})

const emit = defineEmits(['update'])
const dialogVisible = defineModel({
  type: Boolean,
  default: false
})
const { language } = storeToRefs(useAppStore())

const refDialogForm = ref(null)
const formLoading = ref(false)
const formData = ref({
  fileList: []
})
const rules = {
  fileList: g_rules.selectRule('附件')
}
const refUpload = ref(null)

watch(
  () => formData.value.fileList,
  nv => {
    refDialogForm.value.validateField(['fileList'])
  }
)

onMounted(() => {
  //
})

const handleClose = _ => {
  dialogVisible.value = false
}

const handleChange = (file, files) => {
  console.log('handleChange', file, files)
}

const handleExceed = (files, uploadFiles) => {
  // console.log('handleExceed', files, uploadFiles)
  // 清空文件列表
  refUpload.value.clearFiles()
  // 手动添加新文件到上传列表
  const file = files[0]
  file.uid = genFileId() // 生成唯一ID
  refUpload.value.handleStart(file)
}

const handleRemove = file => {
  console.log('handleRemove', file)
  formData.value.base64Image = ''
}

const handleDownloadTemplate = _ => {
  const urlMethod = {
    1: g_api.recipe.apiRecipeDownloadTemplate,
    2: g_api.device.apiDeviceDownloadTemplate,
    3: g_api.foodstuff.apiMaterialDownloadTemplate,
    4: g_api.foodstuff.apiFlavourDownloadTemplate,
    5: g_api.foodstuff.apiProcessDownloadTemplate
  }[props.type]
  console.log('urlMethod', urlMethod)
  urlMethod()
    .then(({ code, data }) => {
      if (code === '200' && data) {
        window.open(data)
      }
    })
    .finally(() => {})
}

const handleViewDetail = _ => {
  window.open(formData.value.data)
}

const handleSubmitForm = () => {
  if (formLoading.value) return
  refDialogForm.value.validate(valid => {
    console.log('formData.value', formData.value)
    if (!valid) return
    formLoading.value = true
    const urlMethod = {
      1: g_api.recipe.apiRecipeImport,
      2: g_api.device.apiDeviceImport,
      3: g_api.foodstuff.apiMaterialImport,
      4: g_api.foodstuff.apiFlavourImport,
      5: g_api.foodstuff.apiProcessImport
    }[props.type]
    const formData2 = new FormData()
    formData2.append('file', formData.value.fileList[0].raw)
    urlMethod(formData2, {
      'Content-Type': 'multipart/form-data' // 关键！
    })
      .then(res => {
        if (res.code === '200') {
          ElMessage({
            message: res.message,
            type: 'success'
          })
          handleClose()
          emit('update')
        }
      })
      .finally(() => {
        formLoading.value = false
      })
  })
}
</script>

<style scoped lang="scss">
:deep(.el-upload-list) {
  margin-top: 0;
  .el-upload-list__item {
    line-height: 24px;
    margin-bottom: 0;
    .el-icon--close-tip {
      color: var(--main-theme);
    }
  }
  .el-upload-list__item.is-success .el-upload-list__item-name:hover {
    color: var(--main-theme);
  }
}
</style>
